import sys
import os
from google.appengine.ext.webapp import template
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.dist import use_library
use_library('django', '0.96')
from os import environ
import models
import datetime
import string
global category
global project
global fields
global name
global ids
flag=False
class MainPage(webapp.RequestHandler,db.Model):
	global category
	global project
	global fields
	global name
	global ids
	def verifyLogin(self):
		user = users.get_current_user()
		if user:
			usercheck=models.userDetails.all()
			usercheck.filter("email =",user.email())
			try:
				currentuser=usercheck.fetch(1)[0]
				userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'")
				for i in userdet:
					if i.privilege=='user':
						return
					elif i.approved==False:
						self.redirect("/usererror")
						return
				self.redirect("/admin")
			except:
				path = os.path.join(os.path.dirname(__file__),'form.html')#use template
				self.response.out.write(template.render(path,{"email":user.email()}))#using template
		else:
			self.redirect(users.create_login_url(self.request.uri))

	def get(self):
		self.verifyLogin()
		global ids
		global category
		global project
		global fields
		ids=self.request.get("ids")
		category=[]
		project=[[],[],[],[],[],[]]
		fields=[]
		c1=db.GqlQuery("SELECT * FROM projectDetails")
		for i in c1:
			if i.projectid==ids:
				self.response.out.write("Hello")
				cat=i.category
		c1=db.GqlQuery("SELECT * FROM projectFields")
     		for i in c1:
			tmp=[]
			tmp.append(i.fieldname.replace(" ","_"))
			tmp.append(i.fieldname)
			category.append(tmp)
		c1=db.GqlQuery("SELECT * FROM projectCategory")
		for i in c1:
			if i.categoryid==cat:
				cat=i.categorytype
		c1=db.GqlQuery("SELECT * FROM projectPool where category='%s'" %cat)
     		for i in c1:
			if i.lock != True:
				project[0].append(i.projectname.replace(" ","_"))
				project[1].append(i.fieldnames.replace(" ","_"))
				project[2].append(i.abstract)
				project[3].append(i.lock)
				project[4].append(i.poolprojectid)	
				project[5].append(i.languages)
		path = os.path.join(os.path.dirname(__file__),'pool.html')#use template
		self.response.out.write(template.render(path,{"category":category},"field"))#using template

	def post(self):    #This is the function which calls topic.html name is the variable being pased
		global category
		global project
		global fields
		global name
		global ids
		name=[]
		path = os.path.join(os.path.dirname(__file__),'topic.html')#use template
		for i in category:
			if self.request.get(i[0])=="yes":
				fields.append(i[0])
		field_names=[]
		f=1
		temp=[]
		if fields :
			q=-1
			for j in project[1]:
				temp=[]
				q=q+1
				field_names=j.split(',')
				e=0
				for k in field_names:
					e=e+1
					temp=[]
					if k in fields:
						flag=True 
					else:
						flag=False
						break
				if len(fields)!=e:
					flag=False
				if flag:
					f=0 
					self.response.out.write(f)
					temp.append(project[0][q])
					temp.append(project[2][q])
					temp.append(project[0][q].replace("_"," "))
					temp.append(project[5][q])
					name.append(temp)
			self.response.out.write(project[5])
			if f==0:
				self.response.out.write(template.render(path,{"name":name,"back":"Back","ids":ids}))#using template

		if len(fields) == 0:
			f=0
			for i in project[0]:
				temp=[]
				temp.append(i)
				temp.append(project[2][project[0].index(i)])
				temp.append(i.replace("_"," "))
				temp.append(project[5][project[0].index(i)])
				name.append(temp)
			self.response.out.write(template.render(path,{"name":name,"back":"Back","ids":ids}))

		if f :						
			path = os.path.join(os.path.dirname(__file__),'rong.html')#use template
			self.response.out.write(template.render(path,{"wro":"wrong","ids":ids}))#,"language":lang}))#using template	
		del field_names[:]
		del fields[:]

class SelectPage(webapp.RequestHandler,db.Model):
	global category
	global project
	global fields
	global name
	global ids
	def get(self):
		f=0
		global category
		global project
		global fields
		global name
		global ids	
		field_names=[]
		f=''
		pro=db.GqlQuery("SELECT * FROM projectDetails ")
		for j in project[0]:
			if self.request.get(j)=="Submit":
				for k in pro:
					if k.projectid==ids:
						k.projectname=j.replace("_"," ")
						prof=db.GqlQuery("SELECT * FROM projectFields")
						project[1][project[0].index(j)]=project[1][project[0].index(j)].replace("_"," ")
						field_names=project[1][project[0].index(j)].split(',')
						for i in prof:
							if i.fieldname in field_names:	
								if(f!=''):
									f=f+","+i.fieldid
								else:
									f=i.fieldid	
						k.fieldnames=f
						f=''
						k.abstract=project[2][project[0].index(j)]	
						lang=project[5][project[0].index(j)].split(',')
						prol=db.GqlQuery("SELECT * FROM languages")
						for i in prol:
							if i.language in lang:
								if(f!=''):
									f=f+","+i.languageid
								else:
									f=i.languageid	
						k.languages=f
						k.confirmed=True
						k.put()
						c1=db.GqlQuery("SELECT * FROM teamDetails")
						for i in c1:
							if i.teamid==k.teamid:
								team=i.teammember.split(",")
						c1=db.GqlQuery("SELECT * FROM userDetails")
						for i in c1:
							if i.admissionnumber in team:
								if i.projectids==None:
									i.projectids=ids
								else:
									i.projectids=i.projectids+','+ids
								i.put()
				c1=db.GqlQuery("SELECT * FROM projectPool")
		     		for i in c1:
					j=j.replace("_"," ")
					if i.projectname==j:	
						f=1
						i.lock=True
						i.put()	
		if f:
			del category[:]
			del project[0][:]
			del project[1][:]
			del project[2][:]
			del name[:]				
			self.redirect("/user")
			
application = webapp.WSGIApplication([('/pool', MainPage),('/sel', SelectPage)],debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()

